package cn.jksoft.businessclient.ui.fragment;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.jksoft.businessclient.R;
import cn.jksoft.businessclient.api.ReceivingService;
import cn.jksoft.businessclient.base.BaseApplication;
import cn.jksoft.businessclient.base.BaseFragment;
import cn.jksoft.businessclient.bean.BaseEntity;
import cn.jksoft.businessclient.bean.ProductCategoryEntity;
import cn.jksoft.businessclient.bean.ProductEntity;
import cn.jksoft.businessclient.bean.ProductInfoEntity;
import cn.jksoft.businessclient.bean.StoreServiceEntity;
import cn.jksoft.businessclient.ui.adapter.ProductCategoryAdapter;
import cn.jksoft.businessclient.ui.adapter.ProductInfoAdapter;
import cn.jksoft.businessclient.ui.views.RecycleViewDivider;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Author:  nick
 * Email:   nickdevp@gmail.com
 * Date:    16/04/07
 * Description:
 */
public class CreateOrderProductFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    @Bind(R.id.swipe_container)
    SwipeRefreshLayout mSwipeLayout;
    @Bind(R.id.recyclerview_product_info)
    RecyclerView mProductInfoRecyclerView;
    @Bind(R.id.recyclerview_product_category)
    RecyclerView mProductCategoryRecyclerView;

    private LinearLayoutManager linearLayoutManager;
    private int lastVisibleItem;
    private boolean isLoadMore;
    private ProductCategoryAdapter categoryAdapter;
    private ProductInfoAdapter infoAdapter;
    private int pageNo = 1;
    private boolean isNoMore;

    private ProgressDialog progressDialog;

    private List<ProductEntity> productList;
    private List<ProductCategoryEntity.StoreProdCataListBean> categoryList;

    private long currentCategoryId;

    private SelectProductListener selectProductListener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_create_order_product, container,
                false);
        ButterKnife.bind(this, view);
        initView();
        return view;
    }

    private void initView() {
        linearLayoutManager = new LinearLayoutManager(getActivity());
        mSwipeLayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));

        mSwipeLayout.setOnRefreshListener(this);
        mSwipeLayout.setColorSchemeResources(R.color.colorPrimary, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, R.color.colorPrimary);
        mSwipeLayout.setDistanceToTriggerSync(400);
        mSwipeLayout.setColorSchemeColors(R.color.white);
        mSwipeLayout.setRefreshing(true);


        //产品分类
        categoryAdapter = new ProductCategoryAdapter(getActivity(), new ArrayList<ProductCategoryEntity.StoreProdCataListBean>());
        mProductCategoryRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mProductCategoryRecyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL));
        categoryAdapter.setItemClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                categoryAdapter.setSelectPosition((int) v.getTag());
                pageNo = 1;
                currentCategoryId = categoryList.get((int) v.getTag()).getPROD_CATA_ID();
                getProductListData(currentCategoryId);

            }
        });
        mProductCategoryRecyclerView.setAdapter(categoryAdapter);

        //产品信息
        mProductInfoRecyclerView.setLayoutManager(linearLayoutManager);
        mProductInfoRecyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL));
        productList = new ArrayList<ProductEntity>();
        infoAdapter = new ProductInfoAdapter(getActivity(), productList);
        infoAdapter.setItemClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ProductEntity bean = productList.get((int) v.getTag());
                selectProductListener.didSelectProduct(bean);
            }
        });
        mProductInfoRecyclerView.setAdapter(infoAdapter);
        mProductInfoRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == infoAdapter.getItemCount()) {
                    if (!isLoadMore) {
                        if (!isNoMore) {
                            getProductListData(currentCategoryId);
                        }
                    }
                    isLoadMore = true;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
            }
        });
        //获取分类列表数据
        getCategoryList();
    }

    private void getCategoryList() {
        JSONObject json = null;
        try {
            json = new JSONObject();
            json.put("storeId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getStoreId() + "");
            json.put("pageSize", "10");
            json.put("pageNo", pageNo + "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        ReceivingService.createReceivingService().getProductCategory(json.toString())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ProductCategoryEntity>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(ProductCategoryEntity entity) {
                        if ("1".equals(entity.getIs_successful())) {
                            if (entity.getStoreProdCataList() != null) {
                                categoryList = entity.getStoreProdCataList();
                                categoryAdapter.addDataList(categoryList);
                                currentCategoryId = categoryList.get(0).getPROD_CATA_ID();
                                getProductListData(currentCategoryId);
                            }
                        }
                    }
                });
    }

    private void getProductListData(long categoryId) {
        mSwipeLayout.setRefreshing(true);
        JSONObject json = null;
        try {
            json = new JSONObject();
            json.put("storeId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getStoreId());
            json.put("prodCataId", categoryId);
            json.put("cataType", "ENT");
        } catch (Exception e) {
            e.printStackTrace();
        }
        ReceivingService.createReceivingService().getProductList(json.toString())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ProductInfoEntity>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mSwipeLayout.setRefreshing(false);
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(ProductInfoEntity entity) {
                        if ("1".equals(entity.getIs_successful())) {
                            if (entity.getStoreProdList() != null) {
                                if (pageNo == 1) {
                                    productList.clear();
                                }
                                if (entity.getStoreProdList().size() >= 10) {
                                    pageNo++;
                                } else {
                                    isNoMore = true;
                                }
                                productList.addAll(entity.getStoreProdList());
                                infoAdapter.notifyDataSetChanged();
                            }
                        } else {
                            showToast(entity.getResult());
                        }
                        mSwipeLayout.setRefreshing(false);

                    }
                });
    }

    @Override
    public void onRefresh() {
        pageNo = 1;
        getProductListData(currentCategoryId);
    }

    public void setSelectProductListener(SelectProductListener selectProductListener) {
        this.selectProductListener = selectProductListener;
    }

    public interface SelectProductListener {
        public void didSelectProduct(ProductEntity entity);
    }
}

